package cn.sylinx.hbatis.ext.parse;

import java.util.Collection;
import java.util.Map;

import cn.sylinx.hbatis.kit.StrKit;
import cn.sylinx.hbatis.log.GLog;
import ognl.Ognl;
import ognl.OgnlException;

/**
 * sql 占位符解析处理器
 * 
 * @author han
 *
 */
public class SqlTokenHandler implements TokenHandler {

	private static final String NOT_NULL_FLAG = "!!";

	private Map<String, Object> params;

	@Override
	public void setParameterMap(Map<String, Object> parameterMap) {
		this.params = parameterMap;
	}

	@Override
	public Object hand(String content) {
		return StrKit.isNotBlank(content) ? (params == null ? null : params.get(content)) : null;
	}

	@Override
	public boolean condition(String condition) {

		if (params == null) {
			return false;
		}

		if (condition == null) {
			return false;
		}

		condition = condition.trim();
		if (condition.startsWith(NOT_NULL_FLAG)) {
			// 空判断
			String trueField = condition.substring(NOT_NULL_FLAG.length()).trim();
			if ("".equals(trueField)) {
				return false;
			}

			Object value = params.get(trueField);
			if (value == null) {
				return false;
			}

			// 如果是字符串，判断是否是空白字符串
			if (value instanceof String) {
				return !"".equals(value.toString());
			}

			// 如果是collection，判断是否有元素
			if (value instanceof Collection) {
				return !((Collection<?>) value).isEmpty();
			}

			return true;
		}

		try {
			Object ret = Ognl.getValue(condition, params);
			if (ret instanceof Boolean) {
				return (Boolean) ret;
			}
		} catch (OgnlException e) {
			GLog.error("Ognl getValue error, exp:" + condition, e);
			return false;
		}

		return false;
	}
}
